<?php


namespace App\Http\Api\Controllers;

use App\Http\Api\Util;
use App\Library\JsonData;
use App\Models\CoComplaint;
use App\Models\CoOrder;
use App\Models\CoOrderComments;
use App\Models\CoUser;
use App\Models\CoUserBalanceLog;
use App\Models\CoUserMoney;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Tests\Models\User;

class UserController extends Controller
{
    public function __construct(Request $request)
    {
        // 调用父类前置方法
        parent::__construct();;
        $this->api_token = trim($request->header('token'));
        $this->get_user();
        if(empty($this->user_info)){
            return JsonData::error('未登录','',601);
        }
        if($this->user_info->type !=1){
            return JsonData::error('用户禁止登录','',601);
        }
    }

    /**
     * @author anbo
     * @method 根据用户id获取当前用户的信息
     * user_id
     * @descrtption 用户进入个人中心页面点击我的信息
     * 所要显示的信息
     */
    public function getUserInfo(Request $request)
    {
        if (!$this->user_info) {
            return JsonData::error( "该用户不存在",'',404);
        } else {
            $type = $request->get('type',1); //1用户 2配送员
            if($type == 1){
                unset($this->user_info->status);
                unset($this->user_info->order_num);
                unset($this->user_info->avatarUrl);
                unset($this->user_info->tel);
            }else{
                if($this->user_info->is_type !=1){
                    return JsonData::error( "该配送员不存在",'',404);
                }
                $this->user_info->avatar = $this->user_info->avatarUrl;
                $this->user_info->mobile = $this->user_info->tel;
                unset($this->user_info->avatarUrl);
                unset($this->user_info->tel);
            }
            $this->user_info->token = $this->user_info->api_token;
            unset($this->user_info->openid);
            unset($this->user_info->api_token);
            return JsonData::success( "获取成功", $this->user_info,200);
        }
    }


    /**
     * 更新用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUser(Request $request){
        try {
            $data =[];
            //赋值
            $nickname = trim($request->nickname);//真实姓名
            $avatar = trim($request->avatar);//头像
            $gender = intval($request->gender);//性别
//            $mobile = trim($request->mobile);//手机号
            //首次设置性别
            if (!in_array($gender,[1,2])) {//前端传了进来
//                $this->user_info->gender = $gender;
                $data['gender'] = $gender;
            }
            if (!empty($nickname)) {//前端传了进来
                $data['nickname'] = $nickname;
//                $this->user_info->nickname = $nickname;
            }
            if (!empty($avatar)) {//前端传了进来
                $data['avatar'] = $avatar;
//                $this->user_info->avatar = $avatar;
            }
//            //设置手机号
//            if (!empty($mobile)) {//前端传了进来
//                //手机号格式
//                if (!preg_match("/^1[34578]\d{9}$/", $mobile)) {
//                    return JsonData::error( "手机号格式不正确",'',602);
//                }
//                $this->user_info->mobile = $mobile;
//            }
            //更新数据
            /*事务begin*/
//            $res =  $this->user_info->save();
            if(!empty($data)){
                $res = DB::table('co_user')->where('id','=',$this->user_info['id'])->update($data);
                if (!$res) {
                    return JsonData::error( "更新失败",'',500);
                } else {
                    return JsonData::success("更新成功",'',200);
                }
            }else{
                return JsonData::error( "参数错误",'',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error( $e->getMessage(),'',500);
        }
    }

    /**
     * 配送员申请
     * @param Request $request
     */
    public function updatedistribution(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                'truename' => 'required|max:32',
                'mobile' => 'required',
                'gender' => 'required|integer|min:1|max:2',
                'idcard' => 'required|alpha_num',
                'idcard_img_r' => 'required',
                'idcard_img_l' => 'required',
                'studentcard_img_r' => 'required',
                'studentcard_img_l' => 'required',
                'school_id'=>'required|integer',
            ]);
            if ($validator->fails()) {
                return JsonData::error($validator->errors()->first());
            }

            if($this->user_info->is_type ==1){
                if($this->user_info->is_shen==1){
                    return JsonData::error( "已是配送员",'',500);
                }
                if($this->user_info->is_shen==0 || $this->user_info->is_shen==0){
                    return JsonData::error( "审核中",'',500);
                }
            }
            $this->user_info->truename = trim($request->truename);//真实姓名
            $this->user_info->gender = intval($request->gender);//性别
            if (!in_array($this->user_info->gender,[1,2])) {
                return JsonData::error( "性别不正确",'',500);
            }
            $this->user_info->tel = trim($request->mobile);//手机号
            if (!preg_match("/^1[345789]\d{9}$/", $this->user_info->tel)) {
                return JsonData::error( "手机号格式不正确",'',500);
            }
            $this->user_info->school_id = intval($request->school_id);//学校
            $this->user_info->idcard = trim($request->idcard);//身份证号
            $this->user_info->student_number = trim($request->student_number);//学号
            $this->user_info->idcard_img_r = trim($request->idcard_img_r);//身份证正面
            $this->user_info->idcard_img_l = trim($request->idcard_img_l);//身份证反面
            $this->user_info->studentcard_img_r = trim($request->studentcard_img_r);//学生证正面
            $this->user_info->studentcard_img_l = trim($request->studentcard_img_l);//学生证反面
            $this->user_info->is_type = 1;
            $this->user_info->is_shen = 0;
            $res = $this->user_info->save();
            if ($res) {
                return JsonData::success( "申请成功",'',200);
            } else {
                return JsonData::error( "申请失败", '',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error( $e->getMessage(),'',500);
        }
    }

    /**
     * 配送收入明细
     */
    public function distribution_info(Request $request){
        try {
            if($this->user_info->is_type !=1){
                return JsonData::error('不是配送员','',500);
            }
            if($this->user_info->is_shen !=1){
                return JsonData::error('用户审核未通过','',500);
            }
            if($this->user_info->status !=1){
                return JsonData::error('用户被禁用','',500);
            }
            $type = $request->get('type',0);
            if(in_array($type,[1,2,3])){
                $data = CoUserBalanceLog::where('user_id',$this->user_info->id)
                    ->where('type',$type)
                    ->orderByDesc('created_at')
                    ->paginate(10);
            }else{
                $data = CoUserBalanceLog::where('user_id',$this->user_info->id)
                    ->orderByDesc('created_at')
                    ->paginate(10);
            }
            return JsonData::success( "返回成功",$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error( $e->getMessage(),'',500);
        }
    }

    /**
     * 配送员提现申请
     */
    public function user_withdrawal(Request $request){
        try {
            if($this->user_info->is_type !=1){
                return JsonData::error('不是配送员','',500);
            }
            if($this->user_info->is_shen !=1){
                return JsonData::error('用户审核未通过','',500);
            }
            if($this->user_info->status !=1){
                return JsonData::error('用户被禁用','',500);
            }
            $money = trim($request->get('money',0));
            if($money <= 0){
                return JsonData::error('金额不正确','',500);
            }
            //查询账余额
            $user = CoUser::where('id',$this->user_info->id)->first();
            if($user->balance < $money){
                return JsonData::error('账号余额不足','',500);
            }
            DB::beginTransaction();
            //创建提现订单
            $CoUserMoney = new CoUserMoney();
            $CoUserMoney->money = $money;
            $CoUserMoney->user_id = $this->user_info->id;
            $snow = new Snowflake();
            $CoUserMoney->order_no =  $snow->id();
            $res = $CoUserMoney->save();
            if($res){
                //扣钱
                //获取用户金额
                $user->balance  = $user->balance  - $money;
                $user->money = $user->money + $money;
                $res = $user->save();
                if($res){
                    DB::commit();
                    return JsonData::success( "申请提现成功",'',200);
                }
            }
            return JsonData::error( "申请提现失败",'',500);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error( $e->getMessage(),'',500);
        }
    }

    /**
     * 投诉或建议
     * @param Request $request
     */
    public function user_complaint(Request $request){
        try {
            $validator = Validator::make($request->all(), [
                "type"=>"required|max:2|min:1",
                "text"=>"required",
                "name"=>"required",
                "tel"=>"required",
                "grade"=>"required|integer|max:10|min:1",
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
//            $grade1 = $request->get('grade1',0);
            //赋值
            $type=$request->type;
            $content=$request->text;
            $name=$request->name;
            $tel=$request->tel;
            $grade=$request->grade;
            //添加投诉建议
            $CoComplaint = new CoComplaint();
            $CoComplaint->type = $type;
            $CoComplaint->content = $content;
            $CoComplaint->name = $name;
            $CoComplaint->tel = $tel;
            $CoComplaint->grade = $grade;
            if($type == 1){
                $grade1 = $request->get('grade1',0);
                if (empty($grade1)) {
                    return JsonData::error('配送员评分未填写','',500);
                }
                $CoComplaint->grade1 = $grade1;
            }
            $res = $CoComplaint->save();
            if($res){
                return JsonData::success('投诉建议成功','',200);
            }else{
                return JsonData::error('投诉建议失败','',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error( $e->getMessage(),'',500);
        }
    }
}
